local skel = fk.CreateSkill {
  name = "emo__chanlie",
  tags = {Skill.Limited},
}

Fk:loadTranslationTable{
  ["emo__chanlie"] = "颤裂",
  [":emo__chanlie"] = "限定技，当你失去最后的手牌或进入濒死状态时，你可以发动此技能：若某点数的牌在弃牌堆中的张数等于其点数，你获得弃牌堆中这些点数所有牌。",

  ["#emo__chanlie-ask"] = "颤裂：你可以发动此技能，获得0张牌",
  ["#emo__chanlie-get"] = "颤裂：你可以获得弃牌堆所有点数为 %arg 的牌",
}

local on_cost = function (self, event, target, player, data)
  local room = player.room
  local map = {}
  for _, id in ipairs(room.discard_pile) do
    local num = Fk:getCardById(id).number
    map[num] = map[num] or {}
    table.insert(map[num], id)
  end
  local get_num = {}
  for num, ids in pairs(map) do
    if #ids == num then
      table.insert(get_num, num)
    end
  end
  local prompt = "#emo__chanlie-ask"
  if #get_num > 0 then
    prompt = "#emo__chanlie-get:::" .. table.concat(get_num, ",")
  end
  if room:askToSkillInvoke(player, {skill_name = skel.name, prompt = prompt}) then
    local get = {}
    for _, num in ipairs(get_num) do
      table.insertTable(get, map[num])
    end
    event:setCostData(self, get)
    return true
  end
end

local on_use = function (self, event, target, player, data)
    local room = player.room
    local get = event:getCostData(self)
    if #get > 0 then
      room:obtainCard(player, get, true, fk.ReasonPrey, player, skel.name)
    end
  end

skel:addEffect(fk.EnterDying, {
  anim_type = "drawcard",
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(skel.name) and player:usedSkillTimes(skel.name, Player.HistoryGame) == 0
  end,
  on_cost = on_cost,
  on_use = on_use,
})

skel:addEffect(fk.AfterCardsMove, {
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(skel.name) and player:isKongcheng() and player:usedSkillTimes(skel.name, Player.HistoryGame) == 0 then
      for _, move in ipairs(data) do
        if move.from == player then
          for _, info in ipairs(move.moveInfo) do
            if (info.fromArea == Card.PlayerEquip) or (info.fromArea == Card.PlayerHand) then
              return true
            end
          end
        end
      end
    end
  end,
  on_cost = on_cost,
  on_use = on_use,
})

return skel
